package com.ybf.api.utils;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.GpsDirectory;
import com.drew.metadata.jpeg.JpegDirectory;

import java.io.IOException;
import java.io.InputStream;

public class FileUtils {
    public static void extractMetadata(InputStream imageFile) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);

            // 获取 EXIF 子 IFD 目录
            ExifSubIFDDirectory exifSubIFDDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if (exifSubIFDDirectory != null) {
                // 获取拍摄时间
                String dateTimeOriginal = exifSubIFDDirectory.getDescription(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
                System.out.println("拍摄时间: " + dateTimeOriginal);

                // 获取设备信息
                String make = exifSubIFDDirectory.getDescription(ExifSubIFDDirectory.TAG_MAKE);
                String model = exifSubIFDDirectory.getDescription(ExifSubIFDDirectory.TAG_MODEL);
                System.out.println("设备制造商: " + make);
                System.out.println("设备型号: " + model);
            }

            // 获取 JPEG 目录
            JpegDirectory jpegDirectory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
            if (jpegDirectory != null) {
                // 获取分辨率
                int width = jpegDirectory.getImageWidth();
                int height = jpegDirectory.getImageHeight();
                System.out.println("分辨率: " + width + "x" + height);
            }

        } catch (ImageProcessingException | IOException e) {
            e.printStackTrace();
        } catch (MetadataException e) {
            throw new RuntimeException(e);
        }
    }
}
